package com.toocms.jinjuhang.ui.cart

import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.RelativeSizeSpan
import androidx.core.graphics.drawable.DrawableCompat
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ResourceUtils
import com.blankj.utilcode.util.StringUtils
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.cart.CartItemData
import com.toocms.jinjuhang.ui.commodity.detils.CommodityDetailsFgt
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.ItemViewModel
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand

class CartItemModel(
    viewModel: CartModel,
    val item: ObservableField<CartItemData>,
    val isSelectedObservableBoolean: ObservableBoolean = ObservableBoolean(false)
) : ItemViewModel<CartModel>(viewModel) {
    val minusObservableField by lazy {
        val rawMinus = ResourceUtils.getDrawable(R.mipmap.icon_minus_gray).mutate()
        DrawableCompat.setTint(rawMinus, 0xFF000000.toInt())
        ObservableField(rawMinus)
    }
    val plusObservableField by lazy {
        val rawPlus = ResourceUtils.getDrawable(R.mipmap.icon_plus_gray).mutate()
        DrawableCompat.setTint(rawPlus, 0xFF000000.toInt())
        ObservableField(rawPlus)
    }

    val minusBindingCommand = BindingCommand<BindingAction>(BindingAction {
        item.get()?.apply {
            val params = mutableMapOf<String, String?>()
            params["member_id"] = UserRepository.user.member_id
            val minQuantityInt = if (min_per?.toInt() ?: 0 > 1) min_per?.toInt() ?: 0 else 1
            val quantityInt = quantity?.toInt() ?: 0
            if (quantityInt > minQuantityInt) {
                params["cart_id"] = cart_id
                viewModel.requestData(
                    Urls.Cart.CART_DEC,
                    params,
                    resultClass = String::class.java,
                    result = {
//                        viewModel.showToast(it)
                        quantity = (quantityInt - 1).toString()
                        item.notifyChange()
                        if (this@CartItemModel.isSelectedObservableBoolean.get()) {
                            viewModel.getTotalAmounts()
                        }
                    })
            } else {
                params["cart_ids"] = cart_id
                viewModel.requestData(
                    Urls.Cart.DEL_FROM_CART,
                    params,
                    resultClass = String::class.java,
                    result = {
//                        viewModel.showToast(it)
                        if (this@CartItemModel.isSelectedObservableBoolean.get()) {
                            this@CartItemModel.isSelectedObservableBoolean.set(false)
                            viewModel.getTotalAmounts()
                        }
                        viewModel.items -= this@CartItemModel
                    })
            }

        }
    })

    val plusBindingCommand = BindingCommand<BindingAction>(BindingAction {
        item.get()?.apply {
            val maxQuantityInt =
                if (max_per?.toInt() ?: 0 > stock?.toInt() ?: 0) stock?.toInt() ?: 0
                else max_per?.toInt() ?: 0
            val quantityInt = quantity?.toInt() ?: 0
            if (maxQuantityInt > quantityInt) {
                val params = mutableMapOf<String, String?>()
                params["member_id"] = UserRepository.user.member_id
                params["cart_id"] = cart_id
                viewModel.requestData(Urls.Cart.CART_INC,
                    params,
                    resultClass = String::class.java,
                    result = {
//                        viewModel.showToast(it)
                        quantity = (quantityInt + 1).toString()
                        item.notifyChange()
                        if (this@CartItemModel.isSelectedObservableBoolean.get()) {
                            viewModel.getTotalAmounts()
                        }
                    })
            }
        }
    })

    val selectClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        isSelectedObservableBoolean.set(!isSelectedObservableBoolean.get())
        viewModel.refreshAllCheckStatus()
        viewModel.getTotalAmounts()
    })

    val itemClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        if (viewModel.isEditObservableBoolean.get()) {
            selectClickBindingCommand.execute()
        } else {
            val bundle = Bundle()
            bundle.putString(Constants.BundleKey.KEY_GOODS_ID, item.get()?.goods_id)
            viewModel.startFragment(CommodityDetailsFgt::class.java, bundle)
        }
    })

    fun price(commodityType: String?, sum: String?) = when (commodityType) {
        Constants.Extra.COMMODITY_TYPE_INTEGRAL -> {
            val sum = if (sum.isNullOrEmpty()) "00" else sum
            SpannableStringBuilder("$sum${StringUtils.getString(R.string.str_integral)}").apply {
                setSpan(
                    RelativeSizeSpan(0.8f), sum.length, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
        else -> {
            val sum = if (sum.isNullOrEmpty()) "0.00" else sum
            "${StringUtils.getString(R.string.str_money_symbol)}$sum"
        }
    }
}